package com.bolehui.base.handle;

import com.alibaba.fastjson.JSONObject;
import com.bolehui.base.result.Result;
import com.bolehui.base.utils.LogUtil;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author chendongjie     email:chendongjie@gz.iscas.ac.cn
 * @version 1.0
 * @ClassName accessDeniedHandler
 * @Description
 * @createTime 2024/12/9 15:44
 * Copyright (C) 2021-2022 CASEEDER, All Rights Reserved.
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的
 */
@Component
public class AccessDefineHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        // 设置响应类型和字符集
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(HttpStatus.FORBIDDEN.value());

        // 准备JSON响应体
        String result = JSONObject.toJSONString(Result.fail("权限不足"));

        // 写入响应
        try (PrintWriter writer = response.getWriter()) {
            writer.write(result);
        } catch (IOException e) {
            // 可以记录日志或者处理异常
            LogUtil.error("处理权限不足出错");
        }
    }
}
